package org.huihoo.orbas.poa;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2003
 * </p>
 * <p>
 * Company: <a href="http://www.huihoo.org/orbas">huihoo.org/orbas</a>
 * </p>
 * 
 * @author <a href="mailto:cocia@163.com">Cocia Lin(cocia@163.com)</a>
 * @version 1.0
 */

public class RequestController extends Thread {
	// ~
	private boolean started;
	private boolean terminaled;
	private org.omg.PortableServer.POA poa;
	private RequestQueue reqQueue;

	// ~
	public RequestController(org.omg.PortableServer.POA poa) {
		this.poa = poa;
		this.reqQueue = new RequestQueue();
		started = false;
		start();
	}

	public boolean started() {
		return started;
	}

	public void terminal() {
		terminaled = true;
	}

	public void begin() {
		started = true;
		notifyAll();
	}

	public boolean terminaled() {
		return terminaled;
	}

	public void run() {
		while (!terminaled()) {
			synchronized (this) {
				if (!started()) {
					try {
						System.out
								.println("RequestController:run():wait for process...");
						wait();
					} catch (InterruptedException ie) {
					}
				}
				dispatchProcessor();
				started = false;
			}
		}

	}

	protected synchronized void dispatchProcessor() {
		while (reqQueue.size() != 0) {
			RequestEntry entry = reqQueue.removeFromHead();
			process(entry);
		}
	}

	protected synchronized void process(RequestEntry entry) {
		RequestProcessor processor = getPoolProcessor();
		processor.init(poa, entry);
		// process.
		processor.process();
	}

	protected synchronized RequestProcessor getPoolProcessor() {

		RequestProcessor processor = new RequestProcessor();

		return processor;
	}

	public void queueRequest(RequestEntry newReq) {
		reqQueue.putToTail(newReq);
		notifyAll();
	}

	private class RequestQueue {
		java.util.List queue;

		public RequestQueue() {
			queue = new java.util.LinkedList();

		}

		public synchronized void putToTail(RequestEntry entry) {
			queue.add(entry);
		}

		public synchronized RequestEntry getFromHead() {
			return (RequestEntry) queue.get(0);
		}

		public synchronized RequestEntry getFromTail() {
			return (RequestEntry) queue.get(queue.size() - 1);
		}

		public synchronized RequestEntry removeFromHead() {
			return (RequestEntry) queue.remove(0);
		}

		public synchronized RequestEntry removeFromTail() {
			return (RequestEntry) queue.remove(queue.size() - 1);
		}

		public synchronized void clear() {

		}

		public synchronized int size() {
			return queue.size();
		}
	}
}